//
//  KRWeatherVC.m
//  QuickCare
//
//  Created by 张凯锐 on 16/7/11.
//  Copyright © 2016年 lidabiao. All rights reserved.
//

#import "KRWeatherVC.h"
#import "KRSelectCityVC.h"
#import <SDCycleScrollView.h>
#import "KRCarouselVC.h"
#import "KRWeatherCollectionCell.h"
#import "KRDiseaseVC.h"
#import <BaiduMapAPI/BMapKit.h>

@interface KRWeatherVC ()<selectCityVCDelegate,UICollectionViewDataSource,UICollectionViewDelegate,BMKLocationServiceDelegate>
//天气图片
@property (weak, nonatomic) IBOutlet UIImageView *weatherImage;
//天气
@property (weak, nonatomic) IBOutlet UILabel *weatherLabel;
//城市
@property (weak, nonatomic) IBOutlet UIButton *city;
//温度
@property (weak, nonatomic) IBOutlet UILabel *temperatureLabel;
//日期
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

//图片轮播
@property (weak, nonatomic) IBOutlet SDCycleScrollView *cycleScrollView;

//名医通
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

//名医通名字数组
@property (nonatomic,strong) NSArray *mytName;
//百度地图定位
@property (nonatomic,strong) BMKLocationService *locService;
//地理编码和反地理编码
@property (nonatomic,strong) CLGeocoder *geocoder;
//定位得到的城市
@property (nonatomic,copy) NSString *name;
@end

@implementation KRWeatherVC
- (void)viewDidLoad {
    [super viewDidLoad];
    //定位方法
    [self baiduLocation];
    
    //名医通名字数组
    NSArray *arr = @[@"肿瘤",@"血液科",@"心血管",@"神经科",@"骨科",@"公益活动"];
    self.mytName = arr;
    
    //图片url数组
    NSArray *imageArray = @[
                     @"http://economy.southcn.com/e/images/attachement/jpg/site4/20160711/0023248fd6ec18ed30d932.jpg",
                     @"http://img2.cache.netease.com/ent/2016/6/14/20160614104559eb061.jpg",
                     @"http://pic.ptfish.com/attachment/forum/201504/16/124208h3it3nen91n4q6ei.jpg",@"http://ent.dzwww.com/nd/201108/W020110816456424146018.jpg"
                     ];
    //将数组给轮播框架轮播
    self.cycleScrollView.imageURLStringsGroup = imageArray;
    //给currentPageDotImage添加一张图片
    self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
    //给pageDotImage添加一张图片
    self.cycleScrollView.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
    //给点击轮播图片添加一个控制器
    [self.cycleScrollView setClickItemOperationBlock:^(NSInteger index) {
        KRCarouselVC *carouselVC = [[UIStoryboard storyboardWithName:@"Carousel" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
        carouselVC.index = index;
        [self.navigationController pushViewController:carouselVC animated:YES];
    }];
    
    //collectionView设置背景色
    self.collectionView.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1.0];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self setUp];
}

#pragma mark - 定位模块
//得到位置后,请求位置的天气
- (void)locationReques {
    NSString *key = @"17IvzuqmKrK1cGwNL6VQebF9";
    
    NSString *url = @"http://api.map.baidu.com/telematics/v3/weather";
    
    NSDictionary *parameters = @{@"location":self.name,@"output":@"json",@"ak":key};
    
    [self requesWeatherURL:url parameter:parameters];
}
//实现定位方法
- (void)baiduLocation {
    //初始化BMKLocationService
    self.locService = [[BMKLocationService alloc]init];
    self.locService.delegate = self;
    //启动LocationService
    [self.locService startUserLocationService];
}
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error || placemarks == nil || [placemarks count] == 0) {
            NSLog(@"地理编码错误");
            return ;
        }
        for (CLPlacemark *pm in placemarks) {
            //需要把locality城市给一个可变字符串再把市给去掉
            NSMutableString *locality = [NSMutableString string];
            [locality appendString:pm.locality];
            NSRange range = [locality rangeOfString:@"市"];
            [locality deleteCharactersInRange:range];
            //把定位得到的城市拿出来
            self.name = locality;
            //所定位到的天气
            [self locationReques];
        }
    }];
    //停止定位
    [self.locService stopUserLocationService];
}

//给collectionView设置属性
- (void)setUp {
    self.flowLayout.minimumLineSpacing = 1;
    self.flowLayout.minimumInteritemSpacing = 1;
    self.flowLayout.itemSize = CGSizeMake((kScreenWidth/3)-1, (self.collectionView.bounds.size.height/2)-1);
    self.collectionView.bounces = NO;
}

#pragma mark - UICollectionViewDataSource数据源
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KRWeatherCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //给cell切圆角
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 5;
    cell.backgroundColor = [UIColor whiteColor];
    cell.name = self.mytName[indexPath.item];
    cell.index = indexPath.item;
    return cell;
}

#pragma mark - UICollectionViewDelegate代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 5) {
        KRCarouselVC *carouselVC = [[UIStoryboard storyboardWithName:@"Carousel" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
        carouselVC.index = 100;
        [self.navigationController pushViewController:carouselVC animated:YES];
    } else {
        //点击cell跳转到疾病界面
        KRDiseaseVC *diseaseVC = [[UIStoryboard storyboardWithName:@"Disease" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
        diseaseVC.diseaseName = self.mytName[indexPath.item];
        diseaseVC.index = indexPath.item;
        [self.navigationController pushViewController:diseaseVC animated:YES];
    }
}

#pragma mark - selectCityVCDelegate刷新定位代理
- (void)refreshLocationDelegate:(KRSelectCityVC *)delegate {
    //再运行一遍定位方法即可
    [self baiduLocation];
}

#pragma mark - selectCityVCDelegate天气代理
//天气网络请求方法代理
- (void)selectCityVCDelegate:(KRSelectCityVC *)selectCity getURL:(NSString *)url parameter:(NSDictionary *)parameter {
    [self requesWeatherURL:url parameter:parameter];
}

//天气网络请求方法
- (void)requesWeatherURL:(NSString *)url parameter:(NSDictionary *)parameter {
    
    [[NetworkManager shareManager] requestWeatherWithURLString:url parameters:parameter success:^(NSDictionary *response) {
        NSArray *results = response[@"results"];
        NSArray *weather_data = results.firstObject[@"weather_data"];
        //日期
        NSString *date = response[@"date"];
        //城市
        NSString *city = results.firstObject[@"currentCity"];
        //天气
        NSString *weather = weather_data.firstObject[@"weather"];
        //温度
        NSString *temperature = weather_data.firstObject[@"temperature"];
        //天气图片
        if ([weather containsString:@"晴转多云"] || [weather containsString:@"多云转晴"]) {
            self.weatherImage.image = [UIImage imageNamed:@"w_qingzhuanduoyun"];
        } else if ([weather containsString:@"晴转雨"] || [weather containsString:@"雨转晴"]) {
            self.weatherImage.image = [UIImage imageNamed:@"w_qingzhuanyu"];
        } else if ([weather containsString:@"雷阵"]){
            self.weatherImage.image = [UIImage imageNamed:@"w_leizhenyu"];
        } else if ([weather containsString:@"雨"]) {
            self.weatherImage.image = [UIImage imageNamed:@"w_xiayu"];
        } else if ([weather containsString:@"多云"] || [weather containsString:@"阴"]) {
            self.weatherImage.image = [UIImage imageNamed:@"w_duoyun"];
        } else if ([weather containsString:@"晴"]) {
            self.weatherImage.image = [UIImage imageNamed:@"w_qingtian"];
        }
        
        self.weatherLabel.text = weather;
        [self.city setTitle:city forState:UIControlStateNormal];
        self.temperatureLabel.text = [NSString stringWithFormat:@"温度:%@",temperature];
        self.dateLabel.text = [NSString stringWithFormat:@"日期:%@",date];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

//跳转到另外一个控制器会执行此方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    //如果是KRSelectCityVC执行代理
    if ([segue.destinationViewController isKindOfClass:[KRSelectCityVC class]]) {
       KRSelectCityVC *vc = segue.destinationViewController;
        vc.delegate = self;
        vc.currentLocation = self.name;
    }
}

//懒加载
- (CLGeocoder *)geocoder {
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

@end
